package netty.tcp.websocket;

import io.netty.channel.Channel;
import org.jctools.maps.NonBlockingHashMap;

public class SessionManager {

    private final static SessionManager sessionManager = new SessionManager();

    private SessionManager() {

    }

    public static SessionManager instance() {
        return sessionManager;
    }


    // session store
    private final NonBlockingHashMap<Integer, Session> userId_channel = new NonBlockingHashMap<>(40000);
    private final NonBlockingHashMap<String, Session> channelId_channel = new NonBlockingHashMap<>(40000);


    public void store(Session session) {
        userId_channel.putIfAbsent(session.getUserId(), session);
        channelId_channel.putIfAbsent(session.getChannelId(), session);
    }

    public int size() {
        return userId_channel.size();
    }

    public void remove(Session session) {
        userId_channel.remove(session.getUserId());
        channelId_channel.remove(session.getChannelId());
    }

    public Session findByChannel(Channel channel) {
        return channelId_channel.get(channel.id().asLongText());
    }

    public Session findByChannelId(int userId) {
        return userId_channel.get(userId);
    }

}
